# -*- coding: utf-8 -*-
import json

from abc import ABC
from tornado.web import RequestHandler
from app.models.cod import Error, code, decription


class CommonHandler(RequestHandler, ABC):
    @property
    def params(self):
        data = self.request.arguments
        data = {
            k: list(map(lambda val: str(val, encoding="utf-8"), v))
            for k, v in data.items()
        }
        return data

    @property
    def common_data(self):
        return ""

    def prepare(self):
        pass

    def json_params(self):
        return json.loads(self.request.body.decode('utf-8'))

    def set_default_headers(self) -> None:
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "*")
        self.set_header('Access-Control-Allow-Methods', '*')
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Private-Network", "true")
        self.set_header("Access-Control-Max-Age", 1000)
        self.set_header("Content-type", "application/json")

    def options(self):
        self.set_status(200)
        self.finish()

    async def response(self, error=Error.No, data=None):
        resp = {
            'code': code(error),
            'message': decription(error),
            'data': data
        }
        self.write(json.dumps(resp))
        await self.finish()

class SmBaseHandler(RequestHandler,ABC):
    def set_default_headers(self) -> None: # 处理普通跨域
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "*")
        self.set_header('Access-Control-Allow-Methods', "*")
        self.set_header("Access-Control-Allow-Credentials", "true")
        self.set_header("Access-Control-Allow-Private-Network", "true")
        self.set_header("Access-Control-Max-Age", 1000)
        self.set_header("Content-type", "application/json")

    def options(self): # 对预检请求进行跨域处理
        self.set_status(200)
        self.finish()